#!/bin/bash

# Eclipse Mosquitto 源码下载准备脚本
# 只负责下载和解压源码，手动进入目录交叉编译

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MOSQUITTO_VERSION="2.0.18"
MOSQUITTO_DIR="mosquitto-${MOSQUITTO_VERSION}"
MOSQUITTO_ARCHIVE="${MOSQUITTO_DIR}.tar.gz"
DOWNLOAD_URL="https://mosquitto.org/files/source/${MOSQUITTO_ARCHIVE}"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}



# 下载源码
download_source() {
    log_info "准备Mosquitto源码..."
    
    cd "$SCRIPT_DIR"
    
    if [ -f "$MOSQUITTO_ARCHIVE" ]; then
        log_info "源码包已存在: $MOSQUITTO_ARCHIVE"
    else
        log_info "下载Mosquitto源码包..."
        if command -v wget >/dev/null 2>&1; then
            wget "$DOWNLOAD_URL"
        elif command -v curl >/dev/null 2>&1; then
            curl -L -O "$DOWNLOAD_URL"
        else
            log_error "需要wget或curl来下载源码包"
            log_info "请手动下载: $DOWNLOAD_URL"
            exit 1
        fi
    fi
    
    if [ -d "$MOSQUITTO_DIR" ]; then
        log_info "清理旧的源码目录..."
        rm -rf "$MOSQUITTO_DIR"
    fi
    
    log_info "解压源码包..."
    tar -xzf "$MOSQUITTO_ARCHIVE"
    
    if [ ! -d "$MOSQUITTO_DIR" ]; then
        log_error "解压失败或目录结构不正确"
        exit 1
    fi
    
    log_info "源码准备完成: $MOSQUITTO_DIR"
}







# 主函数
main() {
    log_info "开始下载Mosquitto源码"
    log_info "版本: $MOSQUITTO_VERSION"
    
    download_source
    
    log_info "源码准备完成！"
    log_info ""
    log_info "接下来请手动进入目录进行交叉编译:"
    log_info "  cd $MOSQUITTO_DIR"
    log_info ""
    log_info "交叉编译方法:"
    log_info "  1. 设置交叉编译环境变量:"
    log_info "     export CC=riscv64-anyka-linux-musl-gcc"
    log_info "     export AR=riscv64-anyka-linux-musl-ar"
    log_info "  2. 进入lib目录编译客户端库:"
    log_info "     cd lib"
    log_info "     \$CC -O2 -Wall -fPIC -I../include -DWITH_THREADING -c mosquitto.c"
    log_info "     \$AR rcs libmosquitto.a mosquitto.o"
    log_info "  3. 使用头文件: include/mosquitto.h"
    log_info "     使用静态库: lib/libmosquitto.a"
}

# 执行主函数
main "$@"